package club.janna.jrpc.rpc.protocol.jrpc;

import club.janna.jrpc.remoting.Channel;
import club.janna.jrpc.remoting.ClientHandler;
import club.janna.jrpc.rpc.RPCInvocation;
import club.janna.jrpc.rpc.RPCResponse;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;

/**
 * @author Panbo.Guo
 */
@Slf4j
public class JRPCClientHandler implements ClientHandler {

    private Map<Integer, CompletableFuture<RPCResponse<?>>> futureMap = new ConcurrentHashMap<>();

    @Override
    public void handleReceive(Channel channel, Object obj) {
        RPCResponse<?> rpcResponse = (RPCResponse<?>) obj;
        log.info("处理方法的返回 -> {}", rpcResponse);
        CompletableFuture<RPCResponse<?>> rpcResponseFuture = futureMap.get(rpcResponse.getId());
        if(rpcResponseFuture == null) {
            log.warn("收到响应，但没有找到对应的请求，response -> {}", rpcResponse);
            return;
        }
        // 完成future
        rpcResponseFuture.complete(rpcResponse);
    }

    @Override
    public Future<RPCResponse<?>> register(RPCInvocation invocation) {
        return futureMap.computeIfAbsent(invocation.getId(), k -> new CompletableFuture<>());
    }
}
